package com.itcs.app.tran;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.itcs.box.BoxConstants;
import com.itcs.box.domain.BoxData;
import com.itcs.box.domain.BoxRequest;
import com.itcs.box.domain.BoxResponse;
import com.itcs.box.util.DateUtils;
import com.itcs.box.util.LogUtils;
import com.itcs.dubbo.service.DubboServiceAdapter;
import com.itcs.trading.mapper.TerminalInfoMapper;
import com.itcs.trading.mapper.TerminalLinksRgtMapper;
import com.itcs.trading.model.TerminalInfo;
import com.itcs.trading.model.TerminalLinksRgt;

/**
 * @ClassName: Tran1001
 * @Description: 连接登录消息
 * @author CHEN-HF
 * @date 2017年12月19日 下午8:47:45
 * 
 */
@Component
public class BoxTran1001 implements DubboServiceAdapter {

	@Autowired
	private TerminalInfoMapper terminalInfoMapper;

	@Autowired
	private TerminalLinksRgtMapper terminalLinksRgtMapper;

	private Log logger = LogFactory.getLog(getClass());

	@Value("${payUrl}")
	private String payUrl; // 支付链接地址

	@Override
	public String getTrancode() {
		return "box_1001";
	}

	public String getTranDescription() {
		return "连接登录消息";
	}

	private void setIinitRepMessage(BoxRequest boxRequest, BoxResponse boxResponse) {
		boxResponse.setMessgeType("2001");// 设置返回消息类型代码
		boxResponse.getData().setDeviceId(boxRequest.getData().getDeviceId());
		boxResponse.getData().setLaneId(boxRequest.getData().getLaneId());
		boxResponse.getData().setPayUrl(payUrl);
	}

	/*
	 * 登录结果：0：登陆成功，-1，密码验证失败，-2：无此设备
	 * 
	 * (non-Javadoc)
	 * 
	 * @see com.itcs.dubbo.service.DubboServiceAdapter#exchange(java.util.Map)
	 */
	@Override
	public Map<String, Object> exchange(Map<String, Object> reqRecord) {

		logger.info(LogUtils.build(getTrancode(), getTranDescription(), "接收登录请求", JSON.toJSONString(reqRecord)));

		BoxResponse boxResponse = new BoxResponse();
		BoxData responseData = new BoxData();
		boxResponse.setData(responseData);

		Map<String, Object> res = new HashMap<>();
		try {
			BoxRequest boxRequest = (BoxRequest) reqRecord.get(BoxConstants.BOX_REQ_KEY);
			this.setIinitRepMessage(boxRequest, boxResponse); // 设置返回数据
			boxResponse = this.handle(boxRequest, boxResponse); // 业务处理
			responseData.setReplyTime(DateUtils.getUnixTimeStamp()); // 回复时间
		} catch (Exception e) {
			responseData.setResult("9"); // 其他异常或数据库异常
			logger.error(LogUtils.build(getTrancode(), getTranDescription(), "处理失败" + e.getMessage(),
					JSON.toJSONString(reqRecord)), e);
		}
		res.put(BoxConstants.BOX_RES_KEY, boxResponse);

		logger.info(LogUtils.build(getTrancode(), getTranDescription(), "返回登陆回复信息(2001)", JSON.toJSONString(res)));

		return res;
	}

	public BoxResponse handle(BoxRequest boxRequest, BoxResponse boxResponse) {

		BoxData data = boxRequest.getData();
		if (StringUtils.isEmpty(data.getPassword())) {
			boxResponse.getData().setResult("2");// 密码校验失败
			return boxResponse;
		}

		// 数据库查找道路、设备
		TerminalInfo lane = terminalInfoMapper.selectByDeviceId(data.getDeviceId());
		// && lane.getLaneId().equals(data.getLaneId()) 暂时不验证laneId
		if (lane != null && lane.getLaneId() != null) {
			// 密码校验
			if (!data.getPassword().equals(lane.getTerminalPwd())) {
				data.setResult("2"); // 密码校验失败
				return boxResponse;
			}

			// 写入盒子链接信息
			TerminalLinksRgt link = new TerminalLinksRgt();
			String channelId = UUID.randomUUID().toString();
			link.setConnectId(channelId);
			boxResponse.setChannelId(channelId);
			// link.setConnectId(boxRequest.getChannelId());
			link.setTerminalNo(Long.parseLong(data.getDeviceId()));
			link.setLinkTime(new Date()); // 连接时间
			link.setLaneId(lane.getLaneId()); // 收费车道编号,收费车道可关联查询收费站、广场、路段信息
			link.setLocalhost(boxRequest.getHost()); // 通道连接ip
			link.setPort(boxRequest.getPort()); // 通道连接端口
			link.setTerminalStatus(null); // 登录后状态是否设置为车道交易状态?是设置1不确定设置null
			link.setTerminalKey(boxRequest.getKey()); // 盒子key信息
			terminalLinksRgtMapper.insert(link);

		} else {
			boxResponse.getData().setResult("3"); // 无此设备
			return boxResponse;
		}

		boxResponse.getData().setResult("1");// 成功返回

		return boxResponse;
	}

}
